package com.caowei.weicimpress.weicimpress.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.GridView;

import com.caowei.weicimpress.weicimpress.R;

/**
 * Created by caoweiPc on 2014/7/28.
 */
public class DeflateGridView extends GridView {
    private OnFinishedlayoutChildren onFinishedlayoutChildren;
    public DeflateGridView(Context context) {
        super(context);
    }

    public DeflateGridView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public DeflateGridView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);

        int numOfColumn= (int) (widthSize/getContext().getResources().getDimension(R.dimen._48dp));
        int count= getAdapter().getCount();
        int numOfRow= (int) Math.ceil(((float)count)/numOfColumn);
        int paddTopaddBottom= this.getPaddingBottom()+this.getPaddingTop();
        int heightSize= Math.round(numOfRow*getContext().getResources().getDimension(R.dimen._48dp)+
                paddTopaddBottom);
        setMeasuredDimension(widthSize,heightSize);
    }

    @Override
    public void requestLayout() {
        super.requestLayout();
        if(onFinishedlayoutChildren!=null){
            onFinishedlayoutChildren.onChildrenLayoutFinished();
        }
        onFinishedlayoutChildren=null;
    }

    public OnFinishedlayoutChildren getOnFinishedlayoutChildren() {
        return onFinishedlayoutChildren;
    }

    public void setOnFinishedlayoutChildren(OnFinishedlayoutChildren onFinishedlayoutChildren) {
        this.onFinishedlayoutChildren = onFinishedlayoutChildren;
    }

    public interface OnFinishedlayoutChildren{
        public void onChildrenLayoutFinished();
    };
}
